package com.my.socket.nio.v1;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * Created by ZhongGang
 * at 2018/6/27 18:24
 */
public class ReverseClient {
    private static final Logger LOGGER = LoggerFactory.getLogger(ReverseClient.class);

    public static void main(String[] args) throws Exception {
        Selector selector = Selector.open();

        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        socketChannel.connect(new InetSocketAddress("127.0.0.1", 9999));
        socketChannel.register(selector, SelectionKey.OP_CONNECT);

        while (true) {
            selector.select();

            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey next = iterator.next();
                try {
                    if (next.isConnectable()) {
                        SocketChannel selectableChannel = (SocketChannel) next.channel();
                        if (selectableChannel.isConnectionPending()) {
                            selectableChannel.finishConnect();
                            LOGGER.info("{}", selectableChannel);

                            ByteBuffer byteBuffer = ByteBuffer.wrap("GET HTTP/1.0".getBytes());
                            selectableChannel.write(byteBuffer);
                        }
                    }
                } catch (Exception e) {
                    LOGGER.error("exception caught, the error is {}", e.getMessage());
                } finally {
                    iterator.remove();
                }
            }
        }
    }
}
